package com.zzx.project.controller;

import com.alibaba.fastjson.JSON;
import com.zzx.project.entity.Leavingmessage;
import com.zzx.project.entity.User;
import com.zzx.project.service.LmService;
import com.zzx.project.service.MaximService;
import com.zzx.project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.zip.DataFormatException;

//用户Controller
@Controller
@RequestMapping("user")
public class UserController { //用户Controller

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    UserService userService;
    @Autowired
    MaximService maximService;
    @Autowired
    LmService lmService;

    //检查用户名是否存在
    @RequestMapping("checkUserName")
    @ResponseBody
    public Object checkUname(@RequestParam("userName") String userName, @RequestParam("userId") Integer userId) {
        HashMap<String, String> map = new HashMap<>();
        System.out.println(userName);
        int exist = userService.checkUname(userName, userId);
        if (exist >= 1) {
            map.put("flag", "true");
        } else {
            map.put("flag", "false");
        }
        return JSON.toJSONString(map);
    }

    //检查邮箱是否存在
    @RequestMapping("checkEmail")
    @ResponseBody
    public Object checkEmail(@RequestParam("userEmail") String userEmail, @RequestParam("userId") Integer userId) {
        HashMap<String, String> map = new HashMap<>();
        System.out.println(userEmail);
        int exist = userService.checkUemail(userEmail, userId);
        if (exist >= 1) {
            map.put("flag", "true");
        } else {
            map.put("flag", "false");
        }
        return JSON.toJSONString(map);
    }

    //检查手机号是否存在
    @RequestMapping("checkPhone")
    @ResponseBody
    public Object checkPhone(@RequestParam("userPhone") String userPhone, @RequestParam("userId") Integer userId) {
        HashMap<String, String> map = new HashMap<>();
        System.out.println(userPhone);
        int exist = userService.checkUphone(userPhone, userId);
        if (exist >= 1) {
            map.put("flag", "true");
        } else {
            map.put("flag", "false");
        }
        return JSON.toJSONString(map);
    }

    //登录
    @RequestMapping("login")
    public String loginCheck(HttpServletRequest request, HttpServletResponse response, User user) {
        String loginType = request.getParameter("logintype");
        String userInfo = user.getUsername(); //此处调出来的也可能会是邮箱以及电话号，与客户端表单内容所填写有关
        String userPass = user.getUserpassword();
        try {
            user = userService.login(userInfo, loginType);
            Cookie userInfo1 = new Cookie("userInfo", userInfo);
            Cookie userPass1 = new Cookie("userPass", userPass);
            userInfo1.setMaxAge(30 * 3600 * 24);
            userPass1.setMaxAge(30 * 3600 * 24);
            userInfo1.setPath("/page/toLogin");
            userPass1.setPath("/page/toLogin");
            response.addCookie(userInfo1);
            response.addCookie(userPass1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (userPass.equals(user.getUserpassword())) {
                try {
                    Date date = user.getUserbirthday();
                    if (date != null) {
                        String strDate = sdf.format(date);
                        Date newDate = sdf.parse(strDate);
                        user.setUserbirthday(newDate);
                    }
                    userService.addLoginCount(user.getUserid());
                    request.getSession().setAttribute("user", user);
                    request.getSession().removeAttribute("tip");
                    request.getSession().setAttribute("LeavingMessages", lmService.getMessagesById(user.getUserid()));
                    return "redirect:/";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                request.getSession().setAttribute("tip", "用户名或密码有误");
                request.setAttribute("userInfo", userInfo);
                request.setAttribute("userPass", userPass);
                return "index";
            }
        }
        return "redirect:/";
    }

    //注册
    @RequestMapping("register")
    public String register(HttpServletRequest request, User user) {
        int flag = userService.addUser(user);
        if (flag > 0) {
            int newUid = userService.getNewUserId();
            Leavingmessage leavingmessage = new Leavingmessage();
            leavingmessage.setLmmessage("欢迎来到EasyShare，尽情享受本站所提供的服务吧");
            leavingmessage.setLmcreateby(1);
            leavingmessage.setLmto(newUid);
            lmService.addMessage(leavingmessage);
            request.getSession().setAttribute("tip", "regSuccess");
            request.setAttribute("userInfo", user.getUsername());
            request.setAttribute("userPass", user.getUserpassword());
        } else {
            request.getSession().setAttribute("tip", "regFalse");
        }
        return "index";
    }

    //退出
    @RequestMapping("exit")
    public String exit(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/";
    }

    //修改个人信息
    @PostMapping("fix")
    public String fixUserInfo(HttpSession session, User user) throws Exception {
        Date date = user.getUserbirthday();
        if (date != null) {
            String strDate = sdf.format(date);
            Date newDate = sdf.parse(strDate);
            user.setUserbirthday(newDate);
            String constellation = getConstellation(strDate);
            user.setUserconstellation(constellation);
        }
        int flag = userService.updateInfo(user);
        if (flag > 0) {
            User user1 = userService.login(user.getUsername(), "userName");
            session.setAttribute("user", user1);
            return "main/about";
        } else {
            throw new DataFormatException();
        }
    }

    //修改密码
    @PostMapping("fixPass")
    @ResponseBody
    public Object fixPass(@RequestParam("uid") int uid, @RequestParam("pass") String pass, @RequestParam("newPass") String newPass, HttpServletRequest request) {
        HashMap<String, String> map = new HashMap<>();
        User user = (User) request.getSession().getAttribute("user");
        if (pass.equals(user.getUserpassword())) {
            int flag = userService.fixPass(uid, newPass);
            if (flag > 0) {
                map.put("flag", "success");
                user.setUserpassword(newPass);
                request.getSession().setAttribute("user", user);
            } else {
                map.put("flag", "exception");
            }
        } else {
            map.put("flag", "ne");
        }
        return map;
    }

    //根据生日获得星座方法
    public String getConstellation(String birthday) {

        String[] constellationArr = {"水瓶座", "双鱼座", "牡羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座",
                "天蝎座", "射手座", "魔羯座"};

        int[] constellationEdgeDay = {20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};

        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date birthDay = formatDate.parse(birthday);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(birthDay);
            int month = calendar.get(Calendar.MONTH);
            int day = calendar.get(Calendar.DATE);
            if (day < constellationEdgeDay[month]) {
                month = month - 1;
            }
            if (month >= 0) {
                return constellationArr[month];
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return constellationArr[11];
    }
}
